<?php

namespace app\admin\service;

use app\admin\dao\UserDao;
use app\admin\model\UM as UM;
use app\admin\traits\AdminCheckTrait;
use app\common\model\Role;
use app\common\model\User;
use ShidianUtil\Exception\DataNotExistException;
use ShidianUtil\Utils\StringUtil;
use think\exception\ValidateException;

/**
 * Class CompanyService
 * @package app\admin\service
 */
class CompanyService
{
    use AdminCheckTrait;

    // dao
    private UserDao $userDao;

    public function __construct(UserDao $userDao)
    {
        $this->userDao = $userDao;
    }

    /**
     * 列表
     * @param UM|null $user
     * @param int|null $page
     * @param int|null $page_size
     * @return array
     */
    public function index(?UM $user, $kw, ?int $page = null, ?int $page_size = null): array
    {
        $companyId = null;
        if (StringUtil::equals($user->roleType, Role::ROLE_TYPE_COMPANY)) {
            $companyId = $user->id;
        }

        //这里如果要修改查询，建议把查询放到dao层去
        return $this->userDao->listCompanies($companyId, $kw, $page, $page_size);
    }

    /**
     * 查询
     * @param UM|null $user
     * @param int $id
     * @return User
     */
    public function read(?UM $user, int $id): ?User
    {
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->userDao->findByPK($id, true);
    }

    /**
     * 新增
     * @param UM $user
     * @param array $params
     * @return  User
     */
    public function add(UM $user, array $params): User
    {
        $this->checkAdmin($user);

        $this->checkRepeat($params['username'], $params['name']);

        $role = Role::where('roleType', Role::ROLE_TYPE_COMPANY)
            ->find();

        if (!$role) {
            throw new ValidateException('不能创建公司');
        }

        $params['roleId'] = $role->id;
        $params['roleType'] = $role->roleType;
        $params['isAdmin'] = '0';
        $params['salt'] = substr(uniqid(), -6);
        $params['password'] = User::signVerifierHash($params['password'], $params['salt']);
        $params['status'] = 1;

        $record = $this->userDao->insertActive($params, []);

        // 写入资金账户 & 获客卡 & 通信币
        $record->account()->save([]);
        $record->card()->save([]);
        $record->coin()->save([]);

        return $record;
    }

    /**
     * 更新
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return User
     */
    public function modify(UM $user, int $id, array $params): User
    {
        if (StringUtil::equals($user->roleType, Role::ROLE_TYPE_COMPANY)) {
            if ($id != $user->id) {
                throw new ValidateException('您只能操作本公司数据');
            }
        } else {
            $this->checkAdmin($user);
        }

        //这里如果要修改查询，建议把查询就放到这里
        $record = User::field(true)
            ->where('id', $id)
            ->where('roleType', Role::ROLE_TYPE_COMPANY)
            ->find();

        if (is_null($record)) {
            throw new DataNotExistException('该公司不存在或已被删除');
        }

        $this->checkRepeat($params['username'], $params['name'], $record->id);

        if (not_blank($params['password'] ?? null)) {
            $params['password'] = User::signVerifierHash($params['password'], $record->salt);
        } else {
            unset($params['password']);
        }

        $allowField = ['username', 'password', 'name', 'desc'];
        $this->userDao->updateActive($record, $params, $allowField);

        // 立即退出登录
        if (isset($params['status']) && $params['status'] == '0') {
            $record->token = '';
            $record->save();
        }

        return $record;
    }

    /**
     * 删除
     * @param UM $user
     * @param int $id
     */
    public function rm(UM $user, int $id): void
    {
        $this->checkAdmin($user);

        //这里如果要修改查询，建议把查询就放到这里
        $record = User::field(true)
            ->where('id', $id)
            ->where('roleType', Role::ROLE_TYPE_COMPANY)
            ->find();

        if (is_null($record)) {
            return;
        }

        $this->userDao->deleteModel($record);
    }

    /**
     * 登录账号不能相同
     * @param $username
     * @param $id
     * @return void
     */
    private function checkRepeat($username, $name, $id = null): void
    {
        $record = User::where(function ($query) use ($username, $name) {
            $query->whereOr('username', $username)
                ->whereOr('name', $name);
        })
            ->when(is_id($id), function ($query) use ($id) {
                $query->where('id', '<>', $id);
            })
            ->find();

        if (!is_null($record)) {
            if (StringUtil::equals($record->username, $username)) {
                throw new ValidateException('该登录名已存在');
            }
            throw new ValidateException('该公司名已存在');
        }
    }

}
